<template>
    <a-modal v-model="visibleFile" :confirmLoading="submitLoading" :closable="false" width="800px">
        <a-alert 
        show-icon
        closable 
        style="margin-bottom:10px" 
        type="info">
        <template #message>
            <p>支持扩展名 .doc、.docx、.xls、.xlsx、.pdf、.png、.jpg、.gif、.jpeg</p>
            <p>单个文件大小不大于10MB，每次上传限制100个文件</p>
        </template>
        </a-alert>

        <a-progress v-if="count>0" status="normal" :percent="count" :format="getProgressText"/>

        <a-tabs :default-active-key="activeKey">
            <a-tab-pane key="1">
                <label slot="tab">
                    <span style="cursor: pointer;">图片</span>
                    <a-badge v-if="imgList.length!==0" :count="imgList.length" style="position: absolute;top:0;left:0;"></a-badge>
                </label>
                <a-empty  v-if="imgList.length ===0" description="暂无数据"/>
                <div class="voucker-pvp" v-for="(item,index) in imgList" :key="index">
                    <img :src="item.url" style="width:108px;height:108px;margin-right:4px;" />
                    <label class="voucker-name">{{item.name}}</label>
                    <p class="voucker-pmp" style="bottom:20px;">
                        <a-icon type="download" style="flex: 1;text-align: left;" @click="fileDownload(item.url)"/>
                        <a-popconfirm title="删除不能恢复，确定删除？" cancelText="取消" okText="确定" @confirm="delImg('imgs',index,item.id)">
                            <a-icon slot="icon" type="question-circle-o" style="color: red" />
                            <a-icon type="delete"/>
                        </a-popconfirm>
                    </p>
                </div>
            </a-tab-pane>
            <a-tab-pane key="2">
                <label slot="tab">
                    <span style="cursor: pointer;">docx文档</span>
                    <a-badge v-if="docList.length!==0" :count="docList.length" style="position: absolute;top:0;left:0;"></a-badge>
                </label>
                <a-empty  v-if="docList.length ===0" description="暂无数据"/>
                <div class="voucker-pvp" v-for="(item,index) in docList" :key="index">
                    <img src="~@/assets/file_doc.png" style="width:108px;height:128px;margin-right:4px;" />
                    <label class="voucker-name">{{item.name}}</label>
                    <p class="voucker-pmp">
                        <a-icon type="download" style="flex: 1;text-align: left;" @click="fileDownload(item.url)"/>
                        <a-popconfirm title="删除不能恢复，确定删除？" cancelText="取消" okText="确定" @confirm="delImg('doc',index,item.id)">
                            <a-icon slot="icon" type="question-circle-o" style="color: red" />
                            <a-icon type="delete" />
                        </a-popconfirm>
                    </p>
                </div>
            </a-tab-pane>
            <a-tab-pane key="3">
                <label slot="tab">
                    <span style="cursor: pointer;">xlsx文档</span>
                    <a-badge v-if="xlsxList.length!==0" :count="xlsxList.length" style="position: absolute;top:0;left:0;"></a-badge>
                </label>
                <a-empty  v-if="xlsxList.length ===0" description="暂无数据"/>
                <div class="voucker-pvp" v-for="(item,index) in xlsxList" :key="index">
                    <img src="~@/assets/file_xlsx.png" style="width:108px;height:128px;margin-right:4px;" />
                    <label class="voucker-name">{{item.name}}</label>
                    <p class="voucker-pmp">
                        <a-icon type="download" style="flex: 1;text-align: left;" @click="fileDownload(item.url)"/>
                        <a-popconfirm title="删除不能恢复，确定删除？" cancelText="取消" okText="确定" @confirm="delImg('xlsx',index,item.id)">
                            <a-icon slot="icon" type="question-circle-o" style="color: red" />
                            <a-icon type="delete" />
                        </a-popconfirm>
                    </p>
                </div>
            </a-tab-pane>
            <a-tab-pane key="4">
                <label slot="tab">
                    <span style="cursor: pointer;">pdf文档</span>
                    <a-badge v-if="pdfList.length!==0" :count="pdfList.length" style="position: absolute;top:0;left:0;"></a-badge>
                </label>
                <a-empty  v-if="pdfList.length ===0" description="暂无数据"/>
                <div class="voucker-pvp" v-for="(item,index) in pdfList" :key="index">
                    <img src="~@/assets/file_pdf.png" style="width:108px;height:128px;margin-right:4px;" />
                    <label class="voucker-name">{{item.name}}</label>
                    <p class="voucker-pmp">
                        <a-icon type="download" style="flex: 1;text-align: left;" @click="fileDownload(item.url)"/>
                        <a-popconfirm title="删除不能恢复，确定删除？" cancelText="取消" okText="确定" @confirm="delImg('pdf',index,item.id)">
                            <a-icon slot="icon" type="question-circle-o" style="color: red" />
                            <a-icon type="delete" />
                        </a-popconfirm>
                    </p>
                </div>
            </a-tab-pane>
        </a-tabs>

        <template slot="footer">
            <input type="file" ref="fileType" @change="handleChange" style="display: none;" multiple="multiple" />
            <a-button type="primary" style="float: left" @click="$refs.fileType.click()">批量上传文件</a-button>
            <a-button @click="visibleFile = false">取消</a-button>
            <a-button @click="handleOtehrFileOk" :disabled="btnState" type="primary">保存</a-button>
        </template>

    </a-modal>
</template>
<script>
import { 
    sysBaseUploadLayout,
    sysBaseGetUploadLayout,
    sysBaseDelUploadLayout,
    sysBaseUpload
} from '@/api/manage/base'
import { 
    previewFile
} from '@/utils/util'
    export default {
        name: 'layoutFile',
        data(){
            return {
                visibleFile:false,
                activeKey:"1",
                settleBatchCode:'',
                imgList:[],
                docList:[],
                xlsxList:[],
                pdfList:[],
                filesList:[],
                count:0,
                flag:false,
                submitLoading:false
            }
        },
        computed: {
            btnState(){
                var flag = false;
                let filesArray = [];
                let newArray = [].concat(this.imgList,this.xlsxList,this.docList,this.pdfList);
                newArray.forEach(v=>{
                    if(!v.id){
                        filesArray.push(v);
                    }
                })
                if(this.flag === true || this.count !== 100 || filesArray.length === 0){
                    flag = true;
                }
                if(newArray.length === 0){
                    this.count =0;
                }
                return flag;
            },
        },
        methods:{
            async add(row){
                const _this = this;
                this.flag = false;
                this.activeKey = "1";
                this.settleBatchCode = row.settleBatchCode;
                this.count = 0;
                const imgType = ['png','jpg','jpeg','gif'];
                const xlsType = ['xls','xlsx'];
                const docType = ['docx','doc'];
                const pdfType = ['pdf'];
                this.imgList = [];
                this.xlsxList = [];
                this.docList = [];
                this.pdfList = [];
                let counts = 0;
                const type = ['img','doc','xls','pdf'];
                for(var i=0;i<type.length;i++){
                    let params = {settleBatchCode:row.settleBatchCode,type:type[i]}
                    const {code,data} = await sysBaseGetUploadLayout(params);
                    if(code === '1'){
                        counts++;
                        data && data.forEach(item => {
                            let poIndex= item.fileUrl.lastIndexOf("/");
                            let idCardName = item.fileUrl.substr(poIndex+1);
                            let index= idCardName.lastIndexOf(".");
                            let fileName = idCardName.substring(0,index);
                            let fileIndex= item.fileUrl.lastIndexOf(".");
                            let _fileType = item.fileUrl.substr(fileIndex+1);
                            if(imgType.includes(_fileType)){
                                _this.imgList.push({url:item.fileUrl,name:fileName,id:item.id});
                            }else if(xlsType.includes(_fileType)){
                                _this.xlsxList.push({url:item.fileUrl,name:fileName,id:item.id})
                            }else if(docType.includes(_fileType)){
                                _this.docList.push({url:item.fileUrl,name:fileName,id:item.id})
                            }else if(pdfType.includes(_fileType)){
                                _this.pdfList.push({url:item.fileUrl,name:fileName,id:item.id})
                            }
                        })
                        if(counts === type.length){
                            this.visibleFile = true;
                        }
                    }
                }
            },
            async delImg(type,index,id){
                if(!id){
                    if(type === 'imgs'){
                        this.imgList.splice(index,1);
                    }else if(type === 'doc'){
                        this.docList.splice(index,1);
                    }else if(type === 'xlsx'){
                        this.xlsxList.splice(index,1);
                    }else if(type === 'pdf'){
                        this.pdfList.splice(index,1);
                    }
                }else{
                    let params = {id:id};
                    const {code} = await sysBaseDelUploadLayout(params);
                    if(code === '1'){
                        this.$message.success("操作成功");
                        if(type === 'imgs'){
                            this.imgList.splice(index,1);
                        }else if(type === 'doc'){
                            this.docList.splice(index,1);
                        }else if(type === 'xlsx'){
                            this.xlsxList.splice(index,1);
                        }else if(type === 'pdf'){
                            this.pdfList.splice(index,1);
                        }
                    }
                }
            },
            fileDownload(_url){
                previewFile(_url);
            },
            getProgressText(percent){
                return`${percent}% `
            },
            async handleChange(e) {
                e.preventDefault();
                let _this = this;
                let fileList = e.target.files;
                if(fileList.length===0){
                    e.target.value= "";
                    return;
                }
                if(fileList.length > 100){
                    _this.$message.error("一次上传最多100个文件");
                    e.target.value= "";
                    return;
                }
                this.flag = true;
                this.count = 0;
                const fileType = ['pdf','doc','docx','xlsx','xls','png','jpg','gif','jpeg'];

                for (let i = 0;i < fileList.length;i++){
                    let isLt5M = fileList[i].size / 1024 / 1024 < 10
                    if(!isLt5M){
                        this.count++;
                        this.$message.error('单个文件大小不能超过 10MB!');
                        return;
                    }
                    let fileIndex= fileList[i].name.lastIndexOf(".");
                    let fileName = fileList[i].name.substring(0,fileIndex);
                    let _fileType = fileList[i].name.substr(fileIndex+1);
                    if (!fileType.includes(_fileType)) {
                        _this.count++;
                        _this.$message.error("文件格式错误");
                        e.target.value= "";
                        return;
                    }
                    let formData = new FormData();
                    formData.append("file",fileList[i]);
                    sysBaseUpload(formData).then(response => {
                        const data = response.data;
                        this.count++;
                        const imgType = ['png','jpg','jpeg','gif'];
                        const xlsType = ['xls','xlsx'];
                        const docType = ['docx','doc'];
                        const pdfType = ['pdf'];
                        let _urlIndex= data.lastIndexOf(".");
                        let _urlName = data.substr(_urlIndex+1);
                        if(imgType.includes(_urlName)){
                            _this.imgList.push({url:data,name:fileName,files:fileList[i],id:''});
                        }else if(xlsType.includes(_urlName)){
                            _this.xlsxList.push({url:data,name:fileName,files:fileList[i],id:''})
                        }else if(docType.includes(_urlName)){
                            _this.docList.push({url:data,name:fileName,files:fileList[i],id:''})
                        }else if(pdfType.includes(_urlName)){
                            _this.pdfList.push({url:data,name:fileName,files:fileList[i],id:''})
                        }
                        if (this.count == fileList.length) {
                            this.count = 100;
                            this.flag = false;
                            e.target.value= "";
                            _this.$message.success("操作成功");
                        }
                    }).catch(error => {
                        _this.count = 0;
                        _this.flag = false;
                        e.target.value= "";
                        _this.$message.error("网络不稳定，请重试或联系管理员");
                    })
                }
            },
            async handleOtehrFileOk(){
               
                
                let filesArray = [];
                let newArray = [].concat(this.imgList,this.xlsxList,this.docList,this.pdfList);
                if(newArray.length === 0){
                    this.$message.error('最少上传一个文件！');
                    return;
                }
                newArray.forEach(v=>{
                    if(!v.id){
                        filesArray.push(v.files);
                    }
                })
                
                if(filesArray.length > 0){
                    let count = 0;
                    this.submitLoading = true;
                    const promise = filesArray.map(async v=>{
                        return new Promise(async resolve => {
                            count++;
                            let formData = new FormData();
                            formData.append("settleBatchCode",this.settleBatchCode);
                            formData.append("files",v);
                            await sysBaseUploadLayout(formData);
                            resolve();
                        });
                    })
                    if(count === filesArray.length){
                        this.$message.success('操作成功！');
                        this.visibleFile = false;
                        this.submitLoading = false;
                    }
                }
            },
        }
    }
</script>